<template>
  <div>
    <div>雷达图</div>
    <div ref="target" class="w-full h-full"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  data: Array,
});
console.log("RADAR>props:", props);

let chart = null;
const target = ref(null);

onMounted(() => {
  chart = echarts.init(target.value);
  console.log("chart initialized:", chart); // 检查 chart 对象
  try {
    ChartInit();
  } catch (error) {
    console.error("Error in ChartInit:", error);
  }
});

const ChartInit = () => {
  if (!props.data || props.data.length === 0) {
    console.log("No data to display");
    return;
  }
  const categoryCount = props.data.reduce((acc, item) => {
    if (item !== undefined && item !== null) {
      acc[item] = (acc[item] || 0) + 1;
    }
    return acc;
  }, {});

  // 提取统计结果并只取前六个类别
  const yAxisData = Object.keys(categoryCount)
    .sort((a, b) => categoryCount[b] - categoryCount[a])
    .slice(0, 6);

  const option = {
    radar: {
      center: ["50%", "50%"],
      radius: "85%",
      axisName: {
        textStyle: {
          color: "#05d5ff",
          fontSize: 14,
        },
      },
      shape: "polygon",
      startAngle: 120,
      axisLine: {
        lineStyle: {
          color: "rgba(5,213,255,0.8)",
        },
      },
      splitLine: {
        lineStyle: {
          color: "rgba(5,213,255,0.8)",
        },
      },
      indicator: yAxisData.map((item) => ({
        name: item,
        max: 44,
        min: 0,
      })),
      splitArea: {
        show: false,
      },
    },
    polar: {
      center: ["50%", "50%"],
      radius: "0%",
    },
    // 角度轴
    angleAxis: {
      min: 0,
      // 坐标轴分割间隔
      interval: 5,
      clockwise: false,
    },
    // 径向轴
    radiusAxis: {
      min: 0,
      interval: 20,
      splitLine: {
        show: false,
      },
    },
    series: {
      type: "radar",
      symbol: "circle",
      symbolSize: 8,
      itemStyle: {
        color: "#05d5ff",
      },
      areaStyle: {
        color: "#05d5ff",
        opacity: 0.5,
      },
      lineStyle: {
        width: 2,
        color: "#05d5ff",
      },
      label: {
        show: true,
        color: "#fff",
      },
      data: [
        {
          value: yAxisData.map((item) => categoryCount[item]),
        },
      ],
    },
  };

  // console.log("option:", option); // 检查 option 对象
  try {
    chart.setOption(option);
  } catch (error) {
    console.error("Error setting option:", error);
  }
};

watch(
  () => props.data,
  () => {
    console.log("props.data changed, calling ChartInit"); // 检查是否调用 ChartInit
    try {
      ChartInit();
    } catch (error) {
      console.error("Error in ChartInit on data change:", error);
    }
  }
);
</script>

<style scoped lang="scss"></style>